package yjj.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import yjj.model.web.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Servlet 工具类
 */
public class ServletUtils {
    /**
     * 为 HttpServletResponse 对象添加 json 数据
     */
    public static void renderJson(HttpServletResponse response, String json) throws IOException {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }

    /**
     * 为 HttpServletResponse 对象添加 Result 对象
     */
    public static void renderResult(HttpServletResponse response, Result result) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", result.getCode());
        map.put("message", result.getMessage() != null ? result.getMessage() : "");
        map.put("data", result.getData() != null ? result.getData() : "");

        // 使用 Jackson 将 Map 转为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(map);

        renderJson(response, jsonResponse);
    }
}
